#!/usr/bin/env python
import gfal
import lcg_util
import sys
import os
import re
import time

def printEntries(entries, lines):
    for f in entries:
        if not f.has_key('stat'):
            print '??????????', f['surl']
            continue
        
        mstring = '----------'
        mode = f['stat'][0]
        if mode & 256: 
            mstring = mstring[:1] + 'r' + mstring[2:]
        if mode & 128: 
            mstring = mstring[:2] + 'w' + mstring[3:] 
        if mode & 64:
            mstring = mstring[:3] + 'x' + mstring[4:] 
        if mode & 32:
            mstring = mstring[:4] + 'r' + mstring[5:]
        if mode & 16:
            mstring = mstring[:5] + 'w' + mstring[6:]
        if mode & 8:
            mstring = mstring[:6] + 'x' + mstring[7:]
        if mode & 4:
            mstring = mstring[:7] + 'r' + mstring[8:]
        if mode & 2:
            mstring = mstring[:8] + 'w' + mstring[9:]
        if mode & 1:
            mstring = mstring[:9] + 'x' + mstring[10:]
        
        print mstring,
        print f['stat'][3], # UID
        print f['stat'][4], # Group ID
        print f['stat'][5], # ???
        print f['stat'][6], # Size
        lines.append(f['surl'])
        if f.has_key('locality'):
            print f['locality'],
        else:
            print 'UNKNONW',
        print f['surl'] #, f['stat']
        if f.has_key('subpaths'):
            printEntries(f['subpaths'], lines)

def srmLs(paths, lines, debug=False):
#    print "Doing ls on ", paths
    (returncode, gfal_o, errmsg) = gfal.gfal_init({'surls': paths, 'defaultsetype': 'srmv2', 'setype': 'srmv2', 'no_bdii_check': 1, 'srmv2_lslevels':1})
    if returncode:
        print "gfal_init failed:", returncode, "Error:", errmsg
        return returncode

    (returncode, gfal_o, errmsg) = gfal.gfal_ls(gfal_o)
    if returncode != 0:
        print "gfal_ls failed:", returncode, "Error:", errmsg
        return returncode
    
    (returncode, gfal_o, filestatuses) = gfal.gfal_get_results(gfal_o)
    if returncode == 0:
        print "gfal_get_results failed:", returncode, "Error:", errmsg  
        return -1

    printEntries(filestatuses, lines)

    gfal.gfal_internal_free(gfal_o)
    
    return 0
